package com.itany.shop.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author MissChen
 * @date 2024年05月16日 13:59
 */
@WebServlet("/showCode")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        //在内存中定义一个画板
        BufferedImage image = new BufferedImage(50, 25, BufferedImage.TYPE_INT_RGB);

        //获取画板中对应的画笔
        Graphics graphics = image.getGraphics();

        //指定画笔填充矩形区域
        graphics.fillRect(0, 0, 50, 25);

        //设置画笔的颜色，设置一个随机色
        graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));

        //设置画笔对应的字体样式
        graphics.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, 18));

        //验证码的内容，要求:随机数字或者英文字母
        String s = "0123456789abcdefghijklmnopqrstuvwxyz";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        //生成验证码后需要用户输入的验证码进行校验
        // 为了便于读取图片中的验证码内容
        // 在此处可以将验证码存到session中去
        request.getSession().setAttribute("code", buffer.toString());
        System.out.println("验证码:" + buffer);

        //将随机生成的字符绘制到图片中
        graphics.drawString(buffer.toString(), 5, 18);

        //输出图片
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
}
